import { nextTick, reactive, ref, watch, onBeforeUnmount } from 'vue'
import { ProductApi } from '@/api/product'
import type { AttrModel, AttrValueModel } from '@/api/product/type'
import useCategoryStore from '@/store/modules/category'
import { ElMessage } from 'element-plus'

// 商品属性逻辑
export const useAttr = () => {
  const categoryStore = useCategoryStore()

  const scene = ref<number>(0)
  const isLoading = ref<boolean>(false)
  const attrList = ref<AttrModel[]>([])
  const attrParam = reactive<AttrModel>({
    id: '',
    categoryId: 0,
    categoryLevel: 3,
    attrName: '',
    attrValueList: [],
    createTime: '',
    updateTime: ''
  })

  const inputRefArr = ref<HTMLInputElement[]>([])

  onBeforeUnmount(() => categoryStore.$reset())

  watch(
    () => categoryStore.c3,
    () => getAttrList()
  )

  const getAttrList = async () => {
    attrList.value = []
    const { c1, c2, c3 } = categoryStore
    
    if (!c3) return
    isLoading.value = true
    attrList.value = await ProductApi.getAttrList(c1, c2, c3)
    isLoading.value = false
  }

  // 添加平台属性，切换场景，禁用三级分类
  const changeScene = (row?: AttrModel) => {
    if (row) {
      Object.assign(attrParam, JSON.parse(JSON.stringify(row)))
    } else {
      Object.assign(attrParam, {
        id: '',
        categoryId: categoryStore.c3,
        categoryLevel: 3,
        attrName: '',
        attrValueList: [],
        createTime: '',
        updateTime: ''
      })
    }

    scene.value = 1
  }

  // 添加属性值按钮事件
  const addAttrValueHandle = (): void => {
    attrParam.attrValueList.push({
      id: '',
      attrId: '',
      valueName: '',
      editMode: true
    })
    // inputRef最后一个组件实例获取焦点
    nextTick(() => inputRefArr.value[attrParam.attrValueList.length - 1].focus())
  }

  // 取消事件
  const cancelHandle = (): number => (scene.value = 0)

  // 输入框失去焦点事件
  const onInputBlur = (row: AttrValueModel, $index: number): void => {
    // 如果输入的属性值为空，则提示错误
    if (row.valueName.trim() == '') {
      ElMessage.error('属性值不能为空')
      attrParam.attrValueList.splice($index, 1)
      return
    }
    // 如果输入是重复的元素
    let isRepeat = attrParam.attrValueList.find((item: AttrValueModel) => {
      if (item != row) {
        return item.valueName == row.valueName
      }
    })
    if (isRepeat) {
      ElMessage.error('属性值已经存在')
      attrParam.attrValueList.splice($index, 1)
      return
    }
    row.editMode = false
  }

  // div点击事件
  const onDivClick = (row: AttrValueModel, $index: number) => {
    row.editMode = true
    nextTick(() => {
      inputRefArr.value[$index].focus()
    })
  }

  // 删除属性
  const deleteAttrHandle = async (row: AttrModel) => {
    try {
      await ProductApi.deleteAttr(row.id)
      ElMessage.success('属性删除成功')
      await getAttrList()
    } catch (error) {}
  }

  // 提交事件
  const submitHandle = async () => {
    // 发送请求
    try {
      await ProductApi.editAttr(attrParam)
      scene.value = 0
      await getAttrList()
      ElMessage.success('属性添加成功')
    } catch (error) {}
  }

  return {
    scene,
    isLoading,
    attrList,
    attrParam,
    inputRefArr,
    categoryStore,
    changeScene,
    addAttrValueHandle,
    cancelHandle,
    onInputBlur,
    onDivClick,
    deleteAttrHandle,
    submitHandle
  }
}
